package com.qf.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.qf.common.BusinessException;
import com.qf.entity.Stock;
import com.qf.mapper.StockMapper;
import com.qf.service.IStockService;
import com.qf.vo.GoodsStockInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {

    @Transactional
    @Override
    public Boolean lockGoodsStock(List<GoodsStockInfo> list) {
        for (GoodsStockInfo gs : list) {
            // 在扣钱库存的时候需要满足3个条件
            // 1.商品id要有，2，仓库的id，3:商品的库存必须要大于等于已经扣减的库存+本次扣减的库存
            int i = baseMapper.lockGoodsStock(gs.getGid(), gs.getWid(), gs.getSum());
            // 如果大于0说明扣减库存成功
            // 如果扣减库存失败(只要有一个失败)全部都回滚
            if (i <= 0) {
                log.warn("扣减【{}】商品库存失败", gs.getGid());
                throw new BusinessException(2003, "扣减库存失败");
            }
        }
        return true;
    }

    @Override
    public void unlockGoodsStock(List<GoodsStockInfo> list) {
        for (GoodsStockInfo gs : list) {
            baseMapper.unlockGoodsStock(gs.getGid(),gs.getWid(),gs.getSum());
        }
    }
}
